package com.vc.desktop.web.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.vc.service.RemoteService;

@Controller
public class DesktopController {

	@Autowired
	private RemoteService remoteService;
	
	@RequestMapping("buy/{marketId}")
	public void queryBuyOrders(ModelMap model, HttpServletResponse response,
			@PathVariable String marketId) throws IOException {
		response.getWriter().println(remoteService.findRawBuyOrders(marketId));
	}
	
	@RequestMapping("sell/{marketId}")
	public void querySellOrders(ModelMap model, HttpServletResponse response,
			@PathVariable String marketId) throws IOException {
		response.getWriter().println(remoteService.findRawSellOrders(marketId));
	}
	
	@RequestMapping("his/{marketId}")
	public void queryHisOrders(ModelMap model, HttpServletResponse response,
			@PathVariable String marketId) throws IOException {
		response.getWriter().println(remoteService.findRawHisOrders(marketId));
	}
	
	@RequestMapping("chart/{marketId}")
	public void queryChartData(ModelMap model, HttpServletResponse response,
			@PathVariable String marketId) throws IOException {
		byte[] bytes = remoteService.findRawChartData(marketId).getBytes();
		OutputStream out = response.getOutputStream();
		int size = bytes.length;
		for (int i = 0; i < size; i++) {
			out.write(bytes[i]);
			if (i % 1024 == 0) {
				out.flush();
			}
		}
		out.flush();
	}
	
	@RequestMapping("market/{marketId}/{code}")
	public String index(ModelMap model,
			@PathVariable String marketId,
			@PathVariable String code) {
		model.addAttribute("marketId", marketId);
		String codes[] = code.split("_");
		model.addAttribute("primaryCode", codes[0]);
		model.addAttribute("secondCode", codes[1]);
		model.addAttribute("btcPrice", remoteService.findBtcPrice());
		model.addAttribute("ltcPrice", remoteService.findLtcPrice());
		model.addAttribute("market", remoteService.findMarketById(marketId));
		model.addAttribute("markets", remoteService.findAllMarkets());
		return "desktop/index";
	}
	
}
